package com.product.Dao.impl;

import com.product.Dao.LoginDao;
import com.product.pojo.Login;
import com.product.pojo.Product;
import com.product.util.DBUtil;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

public class LoginDaoImpl implements LoginDao {
    @Override
    public int insert(Login login) {
        PreparedStatement ps=null;
        int count=0;
        try {
            Connection conn=DBUtil.getConnection();
            String sql="insert into product_user(username,password,email) values(?,?,?)";
            ps=conn.prepareStatement(sql);
            ps.setString(1,login.getUsername());
            ps.setString(2,login.getPassword());
            ps.setString(3,login.getEmail());
            count= ps.executeUpdate();
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }finally {
            DBUtil.close(null,ps,null);
        }

        return count;
    }

    @Override
    public int deleteByName(String name) {
        return 0;
    }

    @Override
    public int update(Login login) {
        PreparedStatement ps=null;
        int count=0;
        try {
            Connection conn=DBUtil.getConnection();
            String sql="update product_user set password=? where email=?";
            ps=conn.prepareStatement(sql);
            ps.setString(1,login.getPassword());
            ps.setString(2,login.getEmail());
            count=ps.executeUpdate();
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }finally {
            DBUtil.close(null,ps,null);
        }
        return count;
    }

    @Override
    public int selectByLoginUser(String username, String password) {
        PreparedStatement ps=null;
        ResultSet rs=null;
        int count=0;
        try {
            Connection conn= DBUtil.getConnection();
            String sql="select * from product_user where username=? and password=?";
            ps=conn.prepareStatement(sql);
            ps.setString(1,username);
            ps.setString(2,password);
            rs= ps.executeQuery();
            if (rs.next()){
                count=1;
            }
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }finally {
            DBUtil.close(null,ps,rs);
        }
        return count;
    }

    @Override
    public List<Login> selectAll() {
        return null;
    }
}
